package com.sijobe.swing;

import java.awt.Color;
import java.awt.Cursor;
import java.awt.Desktop;
import java.awt.Font;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;

import javax.swing.JLabel;

public class JHyperLink extends JLabel implements MouseListener {

   private static final long serialVersionUID = -380989924723873157L;
   private String label;
   private File file;
   private URI uri;
   private boolean isUrl;
   private Cursor previousCursor;

   public JHyperLink(String label, File file) {
      super(label);
      init(label,file,null);
      isUrl = false;
   }
   
   public JHyperLink(String label, URI uri) {
      super(label);
      init(label,null,uri);
      isUrl = true;
   }
   
   /**
    * Does its magic and works out what type of link it is (file or URL currently)
    * 
    * @param label
    * @param link
    */
   public JHyperLink(String label, String link) {
      super(label);
      if (link.startsWith("http://") || link.startsWith("https://")) {
         try {
            init(label,null,new URI(link));
         } catch (URISyntaxException e) {
         }
      } else {
         init(label,new File(link),null);
      }
   }
   
   private void init(String label, File file, URI uri) {
      this.label = label;
      this.uri = uri;
      this.file = file;
      this.setForeground(new Color(0, 0, 255));
      this.setFont(new Font("Tahoma", Font.PLAIN, 9));
      this.addMouseListener(this);
      setUnderlined(true);
      previousCursor = this.getCursor();
   }
   
   private void setUnderlined(boolean underlined) {
      if (underlined) {
         this.setText("<html><body><u>" + label + "</u></body></html>");
      } else {
         this.setText(label);
      }
   }

   public void mouseEntered(MouseEvent arg) {
      setUnderlined(false);
      previousCursor = this.getCursor();
      this.setCursor(Cursor.getPredefinedCursor(Cursor.HAND_CURSOR));
   }

   public void mouseExited(MouseEvent arg) {
      setUnderlined(true);
      this.setCursor(previousCursor);
   }

   public void mouseClicked(MouseEvent arg) {
      if (Desktop.isDesktopSupported()) {
         Desktop d = Desktop.getDesktop();
         if (isUrl) {
            try {
               d.browse( uri );
            } catch (IOException e) {
               System.err.println("Cannot open provided url link.");
            }
         } else {
            try {
               d.open(file);
            } catch (Exception exc) {
               System.err.println("Cannot open provided file link.");
            }
         }
      }
   }

   public void mousePressed(MouseEvent arg) {}
   public void mouseReleased(MouseEvent arg) {}
}
